<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row>
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectIdArr"
          :options="cataList"
          :props="cataProps"
          @change="selectCataChange"></el-cascader>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加参数</el-button>
          <el-table  :data="manyList">
            <el-table-column type="expand">
              <!-- 小标签 -->
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="true" @close="TagClose(scope.row, i)">
                  {{tag}}
                </el-tag>
                <!-- 添加小标签 -->
                <el-input class="input-new-tag" v-if="scope.row.tagVisible" v-model="scope.row.tagValue" size="small" ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="50px"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditdialog(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加属性</el-button>
          <el-table  :data="onlyList">
              <el-table-column type="expand">
              <!-- 小标签 -->
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="true" @close="TagClose(scope.row, i)">
                  {{tag}}
                </el-tag>
                <!-- 添加小标签 -->
                <el-input class="input-new-tag" v-if="scope.row.tagVisible" v-model="scope.row.tagValue" size="small" ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="50px"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditdialog(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数弹框 -->
    <el-dialog :title="'添加'+ titleText"  :visible.sync="adddialogVisible" width="50%" @close="adddialogClose">
      <el-form ref="addFromRef" :model = "addFrom" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name"
        :rules="[{ required: true, message: '请输入参数', trigger: 'blur' }]">
        <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数弹框 -->
    <el-dialog :title="'修改'+ titleText"  :visible.sync="editdialogVisible" width="50%" @close="editdialogClose">
      <el-form ref="editFromRef" :model = "editFrom" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name"
        :rules="[{ required: true, message: '请输入参数', trigger: 'blur' }]">
        <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  created () {
    this.getCatalogList()
  },
  data () {
    return {
      // 被激活的页签
      activeName: 'many',
      // 选择的id数组
      selectIdArr: [],
      // 分类列表
      cataList: [],
      // 级联属性
      cataProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 请求参数列表
      queryInfo: {
        id: '',
        sel: ''
      },
      // 静态参数列表
      onlyList: [],
      // 动态参数列表
      manyList: [],
      // 添加动态参数弹框
      adddialogVisible: false,
      // 添加参数表单对象
      addFrom: {
        attr_name: ''
      },
      // 编辑参数弹框显示与隐藏
      editdialogVisible: false,
      editFrom: { }
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled () {
      if (this.selectIdArr.length !== 3) {
        return true
      }
      return false
    },
    // 动态计算标题文本
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    // 选择分类
    selectCataChange () {
      // 选中的为非3级
      if (this.selectIdArr.length !== 3) {
        this.selectIdArr = []
        this.onlyList = []
        this.manyList = []
      } else {
        console.log(this.selectIdArr)
        this.getParamsList(this.activeName)
      }
    },
    // 获取分类列表
    async getCatalogList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cataList = res.data
      console.log(res)
    },
    tabsClick () {
      if (this.selectIdArr.length !== 3) return this.$message.error('请选择商品分类！')
      this.getParamsList(this.activeName)
    },
    // 获取参数列表
    async getParamsList (params) {
      const { data: res } = await this.$http.get(`categories/${this.selectIdArr[2]}/attributes`, { params: { sel: params } })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.tagVisible = false
        item.tagValue = ''
      })
      if (params === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
    },
    // 显示标签输入框
    showInput (item) {
      item.tagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加新标签
    handleInputConfirm (item) {
      if (item.tagValue.trim().length !== 0) {
        item.attr_vals.push(item.tagValue.trim())
        this.attrValsChange(item)
      }
      item.tagValue = ''
      item.tagVisible = false
    },
    // 标签增减请求
    async attrValsChange (item) {
      const { data: res } = await this.$http.put(`categories/${this.selectIdArr[2]}/attributes/${item.attr_id}`, { attr_name: item.attr_name, attr_sel: this.activeName, attr_vals: item.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 删除标签
    TagClose (item, index) {
      item.attr_vals.splice(index, 1)
      this.attrValsChange(item)
    },
    // 监听添加对话框关闭事件
    adddialogClose () {
      this.$refs.addFromRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addFromRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post(`categories/${this.selectIdArr[2]}/attributes`, { attr_name: this.addFrom.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.getParamsList(this.activeName)
        this.adddialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 响应修改按钮
    async showeditdialog (attrId) {
      // 查询参数
      const { data: res } = await this.$http.get(`categories/${this.selectIdArr[2]}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editFrom = res.data
      this.editdialogVisible = true
    },
    // 监听修改对话框关闭事件
    editdialogClose () {
      this.$refs.editFromRef.resetFields()
    },
    // 确认修改
    editParams () {
      this.$refs.editFromRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put(`categories/${this.selectIdArr[2]}/attributes/${this.editFrom.attr_id}`, { attr_name: this.editFrom.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getParamsList(this.activeName)
        this.editdialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 删除参数
    async removeParams (attrId) {
      const data = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (data === 'cancel') return this.$message({ type: 'info', message: '已取消删除' })
      const { data: res } = await this.$http.delete(`categories/${this.selectIdArr[2]}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsList(this.activeName)
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert{
  margin-bottom: 20px;
}
.el-tag{
  margin-right: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>
